// 申报单位
<template>
    <div>
           <div class="top" v-if="!isShow">
                                            <div class="left">
                                                <div>
                                                    <el-button
                                                        size="mini" class="btn-blue"
                                                        @click="selectUnit"
                                                        >选择申报单位</el-button
                                                    >
                                                    <el-button
                                                        size="mini" class="btn-delete"
                                                        @click="clickUniDel"
                                                        >删除</el-button
                                                    >
                                                </div>
                                            </div>
                                        </div>
                                        <!-- 申报机构 -->
                                        <el-table
                                            class="table"
                                            :data="unitTableData"
                                            border
                                            style="width: 100%"
                                            :row-class-name="tableRowClassName"
                                            :header-cell-style="{
                                                textAlign: 'center'
                                            }"
                                            :cell-style="{
                                                textAlign: 'center'
                                            }"
                                            :max-height="$store.state.tableHeight"
                                            @selection-change="planTableSelect"
                                            ref="table"
                                             v-sortTable="{ 'tableData': unitTableData, '_this': this, 'ref': 'table' }"
                                        >
                                            <el-table-column
                                                v-if="!isShow"
                                                type="selection"
                                                width="55"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                label="年度需用计划编号"
                                                min-width="300"
                                            >
                                            <template slot-scope="{row}">
                                                <span class="a" @click="rowClick(row)">
                                                    {{
                                                        row.annualDemandPlanBillNo
                                                    }}
                                                </span>
                                            </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="orgName"
                                                label="机构名称"
                                                min-width="300"
                                            >
                                            </el-table-column>
                                        </el-table>
                                        <!-- <span>{{test}}</span> -->
                                            <div
                                            class="top"
                                            style="margin-top: 20px"
                                            v-if="!isShow"
                                        >
                                            <div class="left">
                                                <div>
                                                    <el-button
                                                        size="mini" class="btn-greenYellow" @click="clickYearPlanDtls"
                                                        >选择明细</el-button
                                                    >
                                                </div>
                                            </div>
                                        </div>
                                        <!-- 明细 -->
                                        <el-table
                                            class="table"
                                            :data="OrgSonTableData"
                                            border
                                            style="
                                                width: 100%;
                                                margin-top: 20px;
                                            "
                                            :row-class-name="tableRowClassName"
                                            :header-cell-style="{
                                                textAlign: 'center'
                                            }"
                                            :cell-style="{
                                                textAlign: 'center'
                                            }"
                                            :tree-props="{
                                                children: 'children',
                                                hasChildren: 'hasChildren'
                                            }"
                                           :max-height="$store.state.tableHeight"
                                            default-expand-all
                                            row-key="uuid"
                                            ref="table"
                                            v-sortTable="{ 'tableData': OrgSonTableData, '_this': this, 'ref': 'table' }"
                                        >
                                            <el-table-column
                                                label="操作"
                                                fixed
                                                width="100px"
                                                align="left"
                                            >
                                                <template slot-scope="{ row, $index }">
                                                    <i
                                                        class="el-icon-delete"
                                                        style="
                                                            cursor: pointer;
                                                            font-size: 20px;
                                                        "
                                                        @click="deleteEle(row,'OrgSon')"
                                                         v-if="$index > 0&&!isShow"
                                                    ></i>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="materialClassName"
                                                label="物资类别"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="materialName"
                                                label="物资名称"
                                                min-width="150"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="spec"
                                                label="规格型号"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="unit"
                                                label="计量单位"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="texture"
                                                label="材质"
                                                min-width="150"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="price"
                                                label="计划单价"
                                                min-width="150"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="amount"
                                                label="计划金额"
                                                min-width="150"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="quantity"
                                                label="计划数量"
                                                min-width="150"
                                            >
                                                <template
                                                    slot-scope="{ row, $index }"
                                                >
                                                    <span v-if="$index > 0">
                                                        {{ row.quantity }}
                                                    </span>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="approvalQuantity"
                                                label="核准数量"
                                                width="150"
                                            >
                                                <template
                                                    slot-scope="{ row, $index }"
                                                >
                                                    <div
                                                        class="
                                                            history-update-tab
                                                        "
                                                    >
                                                        <el-input
                                                            @input="
                                                                countInput(row)
                                                            "
                                                            v-enter-integer1="{
                                                                set: row,
                                                                key: 'approvalQuantity'
                                                            }"
                                                            v-model="
                                                                row.approvalQuantity
                                                            "
                                                            clearable
                                                            v-if="$index > 0"

                                                        ></el-input>
                                                        <historyUpdateTable
                                                            v-if="
                                                                row.approvalQuantityIsUpdate ===
                                                                1
                                                            "
                                                            @clickIcon="
                                                                clickIcon(
                                                                    row.dtlId,
                                                                    'approvalQuantity'
                                                                )
                                                            "
                                                            :historyTable="
                                                                historyTableData
                                                            "
                                                        />
                                                    </div>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="approvalPrice"
                                                label="核准单价（元）"
                                                width="130"
                                            >
                                                <template
                                                    slot-scope="{ row, $index }"
                                                >
                                                    <div
                                                        class="
                                                            history-update-tab
                                                        "
                                                    >
                                                        <el-input
                                                            @input="
                                                                countInput(row)
                                                            "
                                                            v-model="
                                                                row.approvalPrice
                                                            "
                                                            clearable
                                                            v-if="$index > 0"
                                                            v-enter-float="{
                                                                set: row,
                                                                key: 'changePrice'
                                                            }"

                                                        ></el-input>
                                                        <historyUpdateTable
                                                            v-if="
                                                                row.approvalPriceIsUpdate ===
                                                                1
                                                            "
                                                            @clickIcon="
                                                                clickIcon(
                                                                    row.dtlId,
                                                                    'approvalPrice'
                                                                )
                                                            "
                                                            :historyTable="
                                                                historyTableData
                                                            "
                                                        />
                                                    </div>
                                                </template>
                                            </el-table-column>

                                            <el-table-column
                                                prop="approvalAmount"
                                                label="金额（元）"
                                                width="130"
                                            >
                                                <template slot-scope="{ row }">
                                                    <span>
                                                        {{ row.approvalAmount }}
                                                    </span>
                                                </template>
                                            </el-table-column>

                                            <el-table-column
                                                prop="purchasingUnitName"
                                                width="150"
                                            >
                                                <!-- 录入人可选择，审核中也可由审核人核准数据为准，单选，弹窗选择全集团组织机构数据，支持批量选择。 -->
                                                <template slot="header">
                                                    <span>集中采购单位</span>
                                                    <i
                                                         v-if="OrgSonTableData.length>0"
                                                        slot="suffix"
                                                        class="
                                                            el-input__icon
                                                            el-icon-document-copy
                                                        "
                                                        style="cursor: pointer"
                                                         @click="
                                                            collectUnitName
                                                        "
                                                    ></i>
                                                </template>
                                                <template
                                                    slot-scope="{ row, $index }"
                                                >
                                                    <el-input
                                                        @input="input(row)"
                                                        v-model="
                                                            row.purchasingUnitName
                                                        "
                                                        v-if="$index > 0"
                                                    >
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            style="
                                                                cursor: pointer;
                                                            "
                                                            @click="
                                                               singUnitName(row)
                                                            "
                                                        ></i>
                                                    </el-input>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="procurementMethod"
                                                label="采购方式"
                                                width="150"
                                            >
                                                <template slot="header">
                                                    <span>采购方式</span>
                                                    <i
                                                         v-if="OrgSonTableData.length>0"
                                                        slot="suffix"
                                                        class="
                                                            el-input__icon
                                                            el-icon-document-copy
                                                        "
                                                        style="cursor: pointer"
                                                         @click="
                                                            collectProcurementMethod
                                                        "
                                                    ></i>
                                                </template>
                                                <template slot-scope="{ row,$index  }">

                                                    <el-select v-model="row.procurementMethod" placeholder="请选择" v-if="$index > 0"
                                                 @change="changeProcurementMethod(row)"
                                                        >
                                                        <el-option
                                                            v-for="item in procurementMethodArr"
                                                            :key="item.value"
                                                            :label="item.label"
                                                            :value="item.value">
                                                        </el-option>
                                                    </el-select>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="contractorName"
                                                label="承建单位"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="remarks"
                                                label="备注"
                                                width="100"
                                            >
                                            </el-table-column>
                                        </el-table>
    </div>
</template>

<script>
import { selectDataClient } from '@/utils/common'
import { getAllOrgPage, selectPurchaseType } from '@/api/turnover/ppw'
import { mapMutations, mapState, mapGetters } from 'vuex'
import {  getUuid } from '@/utils/common'
import {
    setYearPlanData,
} from '@/api/turnover/ppw.js'
import planRequest from '@/api/turnover/plan.js'

export default {
    data () {
        return{
            unitTableData: [], //申报机构表格
            localUnitTableData: [], //本地申报单位
            OrgSonTableData: [], //明细表格
            annualDemandPlanBillIdArr: [],
            test: [],
            curRow: {}, //点击申报单位当前行
            uniChecked: [],
            curIndex: [],
            flag: false,
            basicFormAmount: 0, //基本信息的计划金额
        }
    },
    props: {
        billId: {
            type: String,
            default: ''
        },
        isShow: {
            type: Boolean,
            default: false
        }
    },
    computed: {
        ...mapState({
            procurementMethodArr: state=>state.turnover.turnoverData.procurementMethod, //采购方式
            unitTableDataVuex: state=>state.turnover.unitTableData, //申报单位以及明细数据
            materialsSummaryTableDataVuex: state =>
                state.turnover.materialsSummaryTableData, //表格汇总数据
        }),
        ...mapGetters(['unitTableData_get'])
    },
    watch: {
        // 'unitTableData_get': {
        //     handler: function (cur) {
        //         if (cur) {
        //             this.unitTableData = this.unitTableDataVuex
        //         }
        //     },
        //     deep: true
        //     // immediate: true
        // }
    },
    created () {
        this.init()
        this.test = this.unitTableDataVuex
    },
    methods: {
        ...mapMutations(
            'turnover', ['setPlanBillIdArr', 'setUnitTableData', 'setMaterialsSummaryTableData']
        ),
        init () {
            this.getUnitTableData() //获取申报机构和明细

        },
        getUnitTableData () {
            planRequest
                .turnoverCentralizedPurchaseSummaryGetAgencyListByBillId(
                    this.billId
                )
                .then(res => {
                    this.setUnitTableData(res)
                    this.unitTableData = this.unitTableDataVuex
                    if(this.unitTableData.length > 0) {
                        this.rowClick(this.unitTableData[0]) //默认显示第0条
                    }
                    this.rollUp(res)
                })
        },
        //点击选择 选择申报单位 获取申报机构
        selectUnit () {
            // 弹窗选择数据
            console.log(this.unitTableData)
            let ids = this.unitTableData.map(x => x.annualDemandPlanBillId)

            selectDataClient({
                SelectServiceToken:
                    '/turnover/centralizedPurchaseSummary/getAgencyList', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids || [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择申报单位' // 标题
            }).then(val => {
                this.annualDemandPlanBillIdArr = []
                const planBillIdArr = val.map(v=>{
                    v.annualDemandPlanBillId = v.billId,
                    v.annualDemandPlanBillNo = v.billNo
                    return v.billId
                })
                if(planBillIdArr.length === 0) return
                this.setPlanBillIdArr(planBillIdArr) //申报单位的ids数组
                planRequest
                    .turnoverCentralizedPurchaseSummaryGetAgencyListByOrgId(
                        planBillIdArr
                    )
                    .then(res => {
                        this.fn(res)
                        // let count = 0
                        // res.map(v=>{
                        //     v.billId = this.billId
                        //     v.dtls.map(item=>{
                        //         item.children.map(n=>{
                        //             n.billId = this.billId
                        //             //汇总小计
                        //             count += (Number( n.approvalAmount) || 0)
                        //         })
                        //         item.materialName = `小计： ${count}` //总计金额
                        //     })
                        // })
                        // this.$emit('basicFormAmount', count) //把金额传给父子间
                        // this.setUnitTableData(res) //数据存储到vuex
                        // this.unitTableData = this.unitTableDataVuex //先给表1 从vuex取值
                        // this.test = this.unitTableData
                    })
            })
        },
        fn (res) {
            let count = 0
            res.map(v=>{
                v.billId = this.billId
                v.dtls.map(item=>{
                    item.children.map(n=>{
                        n.billId = this.billId
                        //汇总小计
                        count += (Number( n.approvalAmount) || 0)
                    })
                    item.materialName = `小计： ${count}` //总计金额
                })
            })
            this.$emit('basicFormAmount', count) //把金额传给父子间
            this.setUnitTableData(res) //数据存储到vuex
            this.unitTableData = this.unitTableDataVuex //先给表1 从vuex取值
            this.test = this.unitTableData
        },
        // 选年计划明细
        clickYearPlanDtls () {
            console.log(this.OrgSonTableData)
            setYearPlanData(
                this.OrgSonTableData,
                this.curRow.annualDemandPlanBillId,
                this.billId,
                3,
                'momentNeedPlan'
            ).then(res => {
                this.OrgSonTableData = res.OrgSonTableData
            })

        },
        rowClick (row) {
            this.curRow = row
            if (row.dtlId && !this.flag) {
                row.changeType = 2
                this.addOrModify(row, 'sql')
            } else if (this.flag) {
                this.addOrModify(row, '_')
            } else{
                row.changeType = 1
                this.addOrModify(row, 'unSql')
            }
        },
        /***
         * row 当前行
         * source 来源：
         *          detId存在==》来源数据库
         *               不存在==》来演源弹窗
         */
        addOrModify (row, source) {
            let count = 0
            row.dtls.forEach(item => {
                if(source === 'sql' ) item.changeType = 2
                if(source === 'unSql' ) item.changeType = 1
                item.uuid = getUuid()
                item.materialClassName = item.topClassName
                item.children.forEach(v => {
                    //汇总小计
                    count += Number( v.approvalAmount)
                    item.materialName = `小计： ${count}`
                    v.parentId = item.uuid
                    v.uuid = getUuid()
                    v.billId = this.billId
                    if(source === 'sql')  v.changeType = 2
                    if(source === 'unSql')  v.changeType = 1
                })
            })
            this.OrgSonTableData = row.dtls
            this.setUnitTableData(this.unitTableData)
        },
        // 批量选择集中采购单位
        collectUnitName () {
            const PlanBillId = this.unitTableData.find(v=>{
                return this.curRow.annualDemandPlanBillId === v.annualDemandPlanBillId
            }).annualDemandPlanBillId
            getAllOrgPage().then(val=>{
                this.unitTableData.forEach(a => {
                    if(a.annualDemandPlanBillId === PlanBillId) {
                        if (a.dtls) {
                            a.dtls.forEach(b => {
                                b.children.forEach(c => {
                                    c.purchasingUnitId = val.orgId
                                    c.purchasingUnitName = val.orgName
                                    this.reverseSunmary2(c, 1)
                                })
                            })
                        }
                    }

                })
            })

        },
        // 单个选择集中采购单位
        async singUnitName (row) {
            let data = await getAllOrgPage()
            row.purchasingUnitName = data.orgName
            row.purchasingUnitId = data.orgId

            this.reverseSunmary(row, 1)
        },
        // 批量选择采购方式
        collectProcurementMethod () {

            const PlanBillId = this.unitTableData.find(v=>{
                return this.curRow.annualDemandPlanBillId === v.annualDemandPlanBillId
            }).annualDemandPlanBillId
            selectPurchaseType().then(val=>{

                this.unitTableData.forEach(a => {
                    if(a.annualDemandPlanBillId === PlanBillId) {
                        if (a.dtls) {
                            a.dtls.forEach(b => {
                                b.children.forEach(c => {
                                    c.procurementMethod = Number(val.kvValue)

                                    this.reverseSunmary2(c, 2)
                                })
                            })
                        }
                    }

                })
            })

        },
        // 改变采购方式事件
        changeProcurementMethod (row) {
            this.reverseSunmary2(row, 2)

            // 存储vuex
            this.setUnitTableData(this.unitTableData)
        },
        //反写到汇总信息
        reverseSunmary (row, type, flag = true) {
            console.log(this.materialsSummaryTableDataVuex, '222')
            this.materialsSummaryTableDataVuex.forEach(item => {
                item.children.forEach(n => {
                    if (
                        n.materialClassId === row.materialClassId &&
                        n.materialId === row.materialId &&
                        n.texture === row.texture
                    ) {
                        if (type === 2) {
                            flag ?
                                n.procurementMethod = row.procurementMethod :
                                n.procurementMethod = ''
                        } else if (type === 1) {
                            flag ?
                                (n.purchasingUnitName = row.purchasingUnitName,
                                n.purchasingUnitId = row.purchasingUnitId) :
                                n.purchasingUnitName = ''
                            n.purchasingUnitId = ''
                        }
                    }
                })
            })
            this.setMaterialsSummaryTableData(this.materialsSummaryTableDataVuex)
        },

        //反写到汇总信息
        reverseSunmary2 (row, type) {
            const arr = []

            this.unitTableData.forEach(a => {
                if (a.dtls) {
                    a.dtls.forEach(b => {
                        b.children.forEach(n => {
                            if (
                                n.materialClassId === row.materialClassId &&
                                n.materialId === row.materialId &&
                                n.texture === row.texture
                            ) {
                                arr.push(n)
                            }
                        })
                    })
                }

            })
            let newArr =  arr.map(v => v.procurementMethod)
            let num1 = newArr[0]
            let flag
            for (let i = 1; i < newArr.length; i++) {
                if (num1 !== newArr[i]) {
                    flag = false
                    break
                }
            }
            this.reverseSunmary(row, type, flag)
        },
        deleteEle (row) {
            row.changeType = -1
            this.flag = true
            // 存储vuex
            this.rollUp()
            this.setUnitTableData(this.unitTableData)
        },
        // 明细金额向上汇总
        rollUp () {
            this.OrgSonTableData.forEach(item=>{
                var count = 0
                item.children.forEach(v=>{
                    if(v.changeType !== -1) {
                        count += Number(v.approvalAmount) || 0
                        item.materialName = `小计： ${count}`
                    }else{
                        item.materialName = `小计： ${count}`
                    }
                })
            })
        },
        clickBtn () {
            this.test = this.unitTableData
        },
        // 计算金额
        countInput (row) {

            if (row.approvalQuantity > row.quantity) row.approvalQuantity = row.quantity

            row.approvalAmount = Number(row.approvalQuantity * row.approvalPrice).toFixed(2)
            this.rollUp()
            this.fn(this.unitTableData)
            this.setUnitTableData(this.unitTableData)
        },
        //获取用户在 汇总明细-申报机构汇总 表格的已选择项
        planTableSelect (selection) {
            this.uniChecked = selection
        },
        clickUniDel () {
            this.uniChecked.forEach(v=>{
                this.unitTableData.forEach(item=>{
                    if(v.annualDemandPlanBillId === item.annualDemandPlanBillId) {
                        item.changeType = -1
                        item.dtls.forEach(a=>{
                            a.children.forEach(b=>{
                                b.changeType = -1
                            })
                        })
                    }
                })
            })
            this.rollUp ()
            this.setUnitTableData(this.unitTableData)
        },
        //选择行颜色
        rowStyle ({ row }) {
            if(!this.onlyID)return
            if(this.onlyID === row.annualDemandPlanBillId) {
                return {
                    'background-color': 'rgb(179,210,238)!important'
                }
            }
        },
        //申报机构删除逻辑
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
    }
}
</script>

<style lang="scss" scoped>

</style>